package com.gpframework.module.controller.wages;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gpframework.common.annotation.Log;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.wages.domain.GzAttendanceManagement;
import com.gpframework.module.wages.domain.GzPersonnelFoundation;
import com.gpframework.module.wages.domain.req.GzAttendanceManagementAdd;
import com.gpframework.module.wages.domain.req.GzAttendanceManagementReq;
import com.gpframework.module.wages.domain.req.GzAttendanceManagementUpdate;
import com.gpframework.module.wages.domain.req.GzGenerateReq;
import com.gpframework.module.wages.domain.vo.GzAttendanceManagementExcel;
import com.gpframework.module.wages.domain.vo.GzAttendanceManagementVo;
import com.gpframework.module.wages.service.IGzAttendanceManagementService;
import com.gpframework.module.wages.service.IGzPersonnelFoundationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

/**
 * @ClassName GzAttendanceManagementController
 * @Author gpframework
 * @Date 2024-01-19
 * @Version 1.0.0
 * @Description 考勤管理Controller
 */
@Validated
@Api(tags = "考勤管理")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/wages/attendancemanagement" )
public class GzAttendanceManagementController extends BaseController {

    private final IGzAttendanceManagementService iGzAttendanceManagementService;
    private final IGzPersonnelFoundationService iGzPersonnelFoundationService;
 /**
  * @Description 分页
  * @Author gpframework
  * @Date 2024-01-19
  * @Param gzAttendanceManagement
  * @Return TableDataInfo
 */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('wages:attendancemanagement:list')")
    @GetMapping("/list")
    public TableDataInfo<GzAttendanceManagementVo> list(GzAttendanceManagementReq gzAttendanceManagementReq)
    {
        startPage();
        QueryWrapper<GzAttendanceManagement> lqw = new QueryWrapper<GzAttendanceManagement>();
        gzAttendanceManagementReq.generatorQuery(lqw,true);
        List<GzAttendanceManagementVo> list = iGzAttendanceManagementService.listVo(lqw);
        return getDataTable(list);
    }


    @ApiOperation("汇总")
    @PreAuthorize("@ss.hasPermi('wages:attendancemanagement:list')")
    @GetMapping("/listed")
    public TableDataInfo<GzAttendanceManagementVo> listed(GzAttendanceManagementReq gzAttendanceManagementReq)
    {
        startPage();
        QueryWrapper<GzAttendanceManagement> lqw = new QueryWrapper<GzAttendanceManagement>();
        gzAttendanceManagementReq.generatorQuery(lqw,true);
        List<GzAttendanceManagementVo> list = iGzAttendanceManagementService.listVoed(lqw);
        return getDataTable(list);
    }


    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzAttendanceManagement
     * @Return TableDataInfo
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('wages:attendancemanagement:add')" )
    @Log(title = "添加考勤管理" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody GzAttendanceManagementAdd gzAttendanceManagementAdd) {
        GzAttendanceManagement gzAttendanceManagement = Convert.convert(new TypeReference<GzAttendanceManagement>() {}, gzAttendanceManagementAdd);
//        List<GzPersonnelFoundation> list=iGzPersonnelFoundationService.lambdaQuery().eq(GzPersonnelFoundation::getName,gzAttendanceManagement.getName())
//                .list();
//        gzAttendanceManagement.setUserId( CollUtil.isNotEmpty(list)?list.get(0).getId():null);
        return toAjax(iGzAttendanceManagementService.save(gzAttendanceManagement) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzAttendanceManagement
     * @Return TableDataInfo
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('wages:attendancemanagement:edit')" )
    @Log(title = "修改考勤管理" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody List<GzAttendanceManagementUpdate> list) {

        return toAjax(iGzAttendanceManagementService.edit(list) ? 1 : 0);
    }



    /**
     * @Description 导出
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzAttendanceManagement
     * @Return TableDataInfo
     */

    @PreAuthorize("@ss.hasPermi('wages:attendancemanagement:export')" )
    @Log(title = "导出考勤管理" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(GzAttendanceManagementReq gzAttendanceManagementReq) {
        QueryWrapper<GzAttendanceManagement> lqw = new QueryWrapper<GzAttendanceManagement>();
        gzAttendanceManagementReq.generatorQuery(lqw,true);
        List<GzAttendanceManagementVo> list = iGzAttendanceManagementService.listVo(lqw);
        ExcelUtil<GzAttendanceManagementVo> util = new ExcelUtil<GzAttendanceManagementVo>(GzAttendanceManagementVo. class);
        return util.exportExcel(list, "attendancemanagement" );
    }


    @ApiOperation("导出考勤管理模板")
    @Log(title = "导出考勤管理模板" , businessType = BusinessType.EXPORT)
    //@PreAuthorize("@ss.hasPermi('wages:attendancemanagement:importTemplate')")
    @GetMapping("/importTemplate" )
    public AjaxResult exportTemplate() {
        ExcelUtil<GzAttendanceManagementExcel> util = new ExcelUtil<>(GzAttendanceManagementExcel.class);
        return util.exportExcel(GzAttendanceManagementExcel.list(), "考勤管理模板");
    }

    @ApiOperation("导入考勤管理数有提示")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:add')")
    @Log(title = "导入考勤管理数有提示", businessType = BusinessType.INSERT)
    @PostMapping("/import")
    public AjaxResult importListNote(MultipartFile file, boolean updateSupport) throws Exception {
        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }

        // 导入新数据
        ExcelUtil<GzAttendanceManagementVo> util = new ExcelUtil<>(GzAttendanceManagementVo.class);
        List<GzAttendanceManagementVo> excelList = util.importCacheExcel(file.getInputStream());

        String message = iGzAttendanceManagementService.importListNote(excelList, updateSupport);
        return AjaxResult.success(message);
    }




    @ApiOperation("导入考勤管理数据")
    //@PreAuthorize("@ss.hasPermi('wages:attendancemanagement:importList')" )
    @Log(title = "导入考勤管理数据" , businessType = BusinessType.INSERT)
    //@PostMapping("/import")
    public AjaxResult importList(MultipartFile file) throws Exception {

        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }

      // 导入新数据
        ExcelUtil<GzAttendanceManagementVo> util = new ExcelUtil<>(GzAttendanceManagementVo.class);
        List<GzAttendanceManagementVo> excelList = util.importCacheExcel(file.getInputStream());
        List<GzAttendanceManagement> list = Convert.convert(new TypeReference<List<GzAttendanceManagement>>() {}, excelList);
        // 创建Calendar对象
        Calendar calendar = Calendar.getInstance();
        //复制userId
        //复制月度天数 应出勤天数 休息日
        for (int i = 0; i < list.size(); i++) {
            GzPersonnelFoundation gzPersonnelFoundation = iGzPersonnelFoundationService.getOne(new QueryWrapper<GzPersonnelFoundation>()
                    .eq("name", list.get(i).getName())
                    .eq("department_name", list.get(i).getDepartmentName())
                    .eq("del_status", YesNoEnum.NO.getKey()));
            GzAttendanceManagement gzAttendanceManagement = iGzAttendanceManagementService.getOne(new QueryWrapper<GzAttendanceManagement>()
                    .eq("name", list.get(i).getName())
                    .eq("department_name", list.get(i).getDepartmentName())
                    .eq("month", list.get(i).getMonth())
                    .eq("del_status", YesNoEnum.NO.getKey()));
            if (!StringUtils.isEmpty(gzAttendanceManagement))
            {
                list.get(i).setId(gzAttendanceManagement.getId());
            }

            list.get(i).setUserId(gzPersonnelFoundation.getId());
            int month = list.get(i).getMonth().getMonth();
            calendar.set(Calendar.MONTH, month);
            // 获取当前月份的天数
            int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            //月度天数
            list.get(i).setMonthlyDays(Double.valueOf(daysInMonth));
            list.get(i).setRequireDateNdancedays((daysInMonth-gzPersonnelFoundation.getMonthlyDays()));
            list.get(i).setRestDays(gzPersonnelFoundation.getMonthlyDays());
        }
        return iGzAttendanceManagementService.saveOrUpdateBatch(list) ? AjaxResult.success("导入成功") : AjaxResult.error();
    }


    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzAttendanceManagement
     * @Return TableDataInfo
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('wages:attendancemanagement:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult<GzAttendanceManagementVo> getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGzAttendanceManagementService.getVoById(id));
    }


    @ApiOperation("生成考勤")
    //@PreAuthorize("@ss.hasPermi('wages:attendancemanagement:generateAttendance')" )
    @PostMapping("/generateAttendance")
    public AjaxResult generateAttendance(@RequestBody GzGenerateReq gzGenerateReq) throws ParseException {

        List<GzPersonnelFoundation> gzPersonnelFoundations=iGzPersonnelFoundationService.lambdaQuery()
                .list();
        iGzAttendanceManagementService.deleteByMonth(gzGenerateReq.getYearMonth());

        // 创建Calendar对象
        Calendar calendar = Calendar.getInstance();
        int month = gzGenerateReq.getYearMonth().getMonth();
        calendar.set(Calendar.MONTH, month);
        // 获取当前月份的天数
        int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        List<GzAttendanceManagement> gzAttendanceManagements=new ArrayList<>();
        for (GzPersonnelFoundation gzPersonnelFoundation : gzPersonnelFoundations){
            GzAttendanceManagement gzAttendanceManagement=new GzAttendanceManagement();
            gzAttendanceManagement.setMonth(gzGenerateReq.getYearMonth());
            gzAttendanceManagement.setDepartmentName(gzPersonnelFoundation.getDepartmentName());
            gzAttendanceManagement.setUserId(gzPersonnelFoundation.getId());
            gzAttendanceManagement.setName(gzPersonnelFoundation.getName());
            gzAttendanceManagement.setJoinedDate(gzPersonnelFoundation.getJoinedDate());
            gzAttendanceManagement.setOvertimeLate(gzPersonnelFoundation.getIncreaseTemperatureSubsidy());
            gzAttendanceManagement.setOtherSubsidies(gzAttendanceManagement.getOtherSubsidies());

            gzAttendanceManagement.setMonthlyDays(Double.valueOf(daysInMonth));
            gzAttendanceManagement.setRequireDateNdancedays((daysInMonth-gzPersonnelFoundation.getMonthlyDays()));
            gzAttendanceManagement.setRestDays(gzPersonnelFoundation.getMonthlyDays());

            gzAttendanceManagements.add(gzAttendanceManagement);
        }
        iGzAttendanceManagementService.saveBatch(gzAttendanceManagements);
        return AjaxResult.success();
    }

    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-01-19
     * @Param gzAttendanceManagement
     * @Return TableDataInfo
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('wages:attendancemanagement:remove')" )
    @Log(title = "删除考勤管理" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iGzAttendanceManagementService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
